package com.heima.behavior.service.impl;
import java.util.Date;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.mapper.ApUnlikesBehaviorMapper;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApUnlikesBehaviorService;
import com.heima.model.behavior.dtos.UnLikesBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApUnlikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ApUnlikesBehaviorServiceImpl extends ServiceImpl<ApUnlikesBehaviorMapper,ApUnlikesBehavior> implements ApUnlikesBehaviorService {
@Autowired
private ApBehaviorEntryService  apBehaviorEntryService;

    @Override
    public ResponseResult unlike(UnLikesBehaviorDto dto) {
        if (dto==null||dto.getArticleId()==null)
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        if (dto.getType()==null||(dto.getType()!=0&&dto.getType()!=1))
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        ApUser user = AppThreadLocalUtils.getUser();
        Integer id = user==null?null:user.getId();
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(id, dto.getEquipmentId());
        if (apBehaviorEntry==null)
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"没有对应的实体对象");
        ApUnlikesBehavior apUnlikesBehavior = getOne(Wrappers.<ApUnlikesBehavior>lambdaQuery().eq(ApUnlikesBehavior::getArticleId, dto.getArticleId())
                .eq(ApUnlikesBehavior::getEntryId, apBehaviorEntry.getId()));
        if (apUnlikesBehavior==null){
            apUnlikesBehavior=new ApUnlikesBehavior();
            apUnlikesBehavior.setEntryId(apBehaviorEntry.getId());
            apUnlikesBehavior.setArticleId(dto.getArticleId());
            apUnlikesBehavior.setType(Integer.valueOf(dto.getType()));
            apUnlikesBehavior.setCreatedTime(new Date());
            save(apUnlikesBehavior);
        }else {
            apUnlikesBehavior.setType(Integer.valueOf(dto.getType()));
            updateById(apUnlikesBehavior);
        }
        return ResponseResult.okResult();
    }
}
